package com.tanhua.app.exception;

import com.tanhua.api.service.BlackListApi;
import com.tanhua.api.service.QuestionApi;
import com.tanhua.api.service.SettingsApi;
import com.tanhua.app.Interceptor.UserHolder;
import com.tanhua.model.pojo.Question;
import com.tanhua.model.pojo.Settings;
import com.tanhua.model.vo.SettingsVo;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SettingsService {

    @DubboReference
    public SettingsApi settingsApi;

    @DubboReference
    public QuestionApi questionApi;

    @DubboReference
    public BlackListApi blackListApi;


    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();

        // 获取当前用户的Id和手机号
        Long userId = UserHolder.getUserId();
        String phone = UserHolder.getUserMobile();

        vo.setId(userId);
        vo.setPhone(phone);

        // 1. 获取用户陌生人的问题
        Question question = questionApi.findByUserID(userId);
        String strangerQuestion = question == null || StringUtils.isEmpty(question.getTxt())
                ? "你喜欢写代码吗？" : question.getTxt();

        vo.setStrangerQuestion(strangerQuestion);

        // 2. 获取用户的通知数据
        Settings settings = settingsApi.findByUserID(userId);

        if (settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
        }

        return vo;
    }

    // 更新通知数据
    public void saveSetting(Map<String, Boolean> params) {
        // 解析参数
        Boolean likeNotification = params.get("likeNotification");
        Boolean pinglunNotification = params.get("pinglunNotification");
        Boolean gonggaoNotification = params.get("gonggaoNotification");

        // 获取当前用户id
        Long userId = UserHolder.getUserId();

        // 根据用户id查询通知数据
        Settings settings = settingsApi.findByUserID(userId);

        // 校验
        if (settings == null) {
            // 成功，添加数据
            settings = new Settings();
            settings.setUserId(userId);
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setPinglunNotification(pinglunNotification);

            settingsApi.save(settings);
        } else {
            // 失败，更新数据
            settings.setPinglunNotification(pinglunNotification);
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);

            settingsApi.updateByID(settings);
        }

    }
}
